<template>
  <basic-container>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row type="flex" class="row-bg" justify="end">
        <el-form-item>
          <!--<el-button type="primary" @click="handleAgree">同意</el-button>
          <el-button type="danger" @click="handleDisagree">驳回</el-button>-->
          <el-button @click="handleCancel">关闭</el-button>
        </el-form-item>
      </el-row>
      <el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="approvalClick">
          <span>图纸审批信息</span>
        </div>
        <div :class="{approval: this.approvalInfo}">
          <el-form-item label="申请人">
            <el-input :disabled="true" v-model="form.applicantName" />
          </el-form-item>
          <el-form-item label="代号">
            <el-input :disabled="true" v-model="form.drawingNumber" />
          </el-form-item>
          <el-form-item label="名称">
            <el-input :disabled="true" v-model="form.drawingName" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" :disabled="true" v-model="form.comment" />
          </el-form-item>
          <!--<el-form-item label="审批意见">
            <el-input type="textarea" v-model="form.approvalOpinion" />
          </el-form-item>-->
        </div>
      </el-card>
      <el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="processClick">
          <span>流程信息</span>
        </div>
        <div :class="{process: this.processInfo}">
          <el-row type="flex" class="row-bg">
            <el-timeline>
              <el-timeline-item :key="flow.id" :timestamp="flow.createTime" v-for="flow in flowList" placement="top">
                <el-card shadow="hover">
                  <p>{{flow.assigneeName}} 在 [{{flow.createTime}}] 开始处理 [{{flow.historyActivityName}}] 环节</p>
                  <p v-if="flow.historyActivityDurationTime!==''">任务历时 [{{flow.historyActivityDurationTime}}]</p>
                  <p v-if="flow.comment!==''">批复意见: [{{flow.comment}}]</p>
                  <p v-if="flow.endTime!==''">结束时间: [{{flow.endTime}}]</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-row>
        </div>
      </el-card>
      <el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="processTrackClick">
          <span>流程跟踪</span>
        </div>
        <div :class="{processTrack: this.processTrackInfo}">
          <el-row type="flex" class="row-bg">
            <img :src="src" alt="design">
          </el-row>
        </div>
      </el-card>
      <!--<el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="planeDrawClick">
          <span>平面图纸</span>
        </div>
        <div :class="{planeDraw: this.planeDrawInfo}">
          &lt;!&ndash;<el-form-item>
            <el-button @click="planeDrawUpload">上传</el-button>
          </el-form-item>&ndash;&gt;
          <el-form-item v-for="drawing in this.planeDrawingList">
            <a :href="drawing.link" download="下载">{{drawing.originalName}}</a>
            <span style="margin-left: 50px; cursor: pointer; color: #191970" title="签名替换" @click="planeDrawUpload(drawing)"><button>签名替换</button></span>
          </el-form-item>
        </div>
      </el-card>
      <el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="dimensionalDrawClick">
          <span>三维图纸</span>
        </div>
        <div :class="{dimensionalDraw: this.dimensionalDrawInfo}">
          &lt;!&ndash;<el-form-item>
            <el-button @click="dimensionalDrawUpload">上传</el-button>
          </el-form-item>&ndash;&gt;
          <el-form-item v-for="drawing in this.dimensionalDrawingList">
            <a :href="drawing.link">{{drawing.originalName}}</a>
            <span style="margin-left: 50px; cursor: pointer; color: #191970" title="签名替换" @click="dimensionalDrawUpload(drawing)"><button>签名替换</button></span>
          </el-form-item>
        </div>
      </el-card>-->

      <el-card shadow="hover">
        <div slot="header" style="cursor: pointer" @click="planeDrawClick">
          <span>图纸审批</span>
        </div>
        <avue-crud :data="drawingData" :option="drawingOption" v-model="drawingForm" @selection-change="selectionChange"
          ref="drawingTable">
          <template slot="menuLeft">
            <!--<el-button type="primary" @click="handleApproval">审核</el-button>-->
            <el-button type="info" icon="el-icon-download" @click="downloadList"
              :style="{display: this.approvalButton}">下载所选图纸</el-button>
            <el-button type="primary" @click="submitReview" :style="{display: this.approvalButton}">提交审核</el-button>
            <el-button type="info" icon="el-icon-download" @click="downloadByBom"
              :style="{display: this.approvalButton}">已归档图纸下载</el-button>
            <!-- <el-button type="primary" @click="multiClickAgree" :style="{display: this.approvalButton}">复选同意</el-button>
            <el-button type="danger" @click="handleDisagree" :style="{display: this.approvalButton}">驳回</el-button> -->
            <el-button type="primary" @click="reUpload()" :style="{display: this.uploadButton}">重新上传</el-button>
            <el-button type="info" @click="handleHistoryApproval" :style="{display: this.uploadButton}">历史审批</el-button>
          </template>
          <template slot="originalName" slot-scope="scope">
            <a class="buttonText" style="cursor:pointer;color:#0000cc;text-decoration:underline" :href="scope.row.link">
              {{ scope.row.originalName }}
            </a>
          </template>

          <template slot="approvalResult" slot-scope="scope">
            <div >
              <el-radio v-model="scope.row.approvalResult" :label="1">同意</el-radio>
              <el-radio v-model="scope.row.approvalResult" :label="0">驳回</el-radio>
            </div>
          </template>

          <template slot="approvalOpinion" slot-scope="scope">
            <el-input v-model="scope.row.approvalOpinion" />
          </template>
        </avue-crud>
      </el-card>
    </el-form>

    <!--上传附件模态窗口信息-->
    <!--<div v-if="planeAttachBox">
      <el-dialog title="附件上传" append-to-body center :visible.sync="planeAttachBox" width="500px">
        <el-scrollbar style="height:350px;">
          <el-form  ref="planeAttachFormRef" :model="attachForm" label-width="80px" size="small" :rules="ruleForm">
            <el-form-item label="图纸名称" prop="threeFiles" ref="planeElement">
              <el-input :disabled="true" v-model="planeAttach.originalName"/>
            </el-form-item>
            <el-form-item label="平面图纸" prop="attchFiles">
              <el-upload
                class="avatar-uploader"
                action="#"
                drag
                ref="fileUpload"
                :auto-upload="true"
                :multiple="false"
                accept=".xls,.xlsx,.pdf,.dwg"
                :file-list="fileList"
                :on-change="uploadChange"
                :on-success="handleSuccess"
                :on-preview="handlePreview"
                :http-request="planeUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 xls/xlsx/pdf/dwg格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer" >
            <el-button type="primary" @click="planeSubmitAttach('planeAttachFormRef')" size="small" icon="el-icon-check">提 交</el-button>
            <el-button @click="planeAttachBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </span>
        </template>

      </el-dialog>
    </div>-->

    <!--上传附件模态窗口信息-->
    <!--<div v-if="dimensionalAttachBox">
      <el-dialog title="附件上传" append-to-body center :visible.sync="dimensionalAttachBox" width="500px">
        <el-scrollbar style="height:350px;">
          <el-form  ref="dimensionalAttachFormRef" :model="attachForm" label-width="80px" size="small" :rules="ruleForm">
            <el-form-item label="图纸名称" prop="threeFiles" ref="threeElement">
              <el-input :disabled="true" v-model="dimensionalAttach.originalName"/>
            </el-form-item>
            <el-form-item label="三维图纸" prop="threeFiles" ref="threeElement">
              <el-upload
                class="avatar-uploader"
                action="#"
                drag
                ref="threeUpload"
                :auto-upload="true"
                :multiple="false"
                :file-list="threeFileList"
                :on-preview="handlePreview"
                :http-request="dimensionalUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 三维图格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>

          </el-form>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer" >
            <el-button type="primary" @click="dimensionalSubmitAttach('dimensionalAttachFormRef')" size="small" icon="el-icon-check">提 交</el-button>
            <el-button @click="dimensionalAttachBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </span>
        </template>

      </el-dialog>
    </div>-->

    <div v-if="attachBox">
      <el-dialog title="签名附件上传" append-to-body center :visible.sync="attachBox" width="540px">
        <el-scrollbar style="height:530px;">
          <el-form ref="attachFormRef" :model="attachForm" label-width="80px" size="small" :rules="ruleForm">
            <el-form-item label="设备编号">
              <el-input :disabled="true" v-model="this.form.drawingNumber" />
            </el-form-item>
            <el-form-item label="设备名称">
              <el-input :disabled="true" v-model="this.form.drawingName" />
            </el-form-item>
            <el-form-item label="平面图纸" prop="attchFiles">
              <el-upload class="avatar-uploader" action="#" drag ref="fileUpload" :auto-upload="true" :multiple="true"
                accept=".xls,.xlsx,.pdf,.dwg,.PDF,.DWG" :file-list="fileList" :on-change="uploadChange"
                :on-success="handleSuccess" :on-preview="handlePreview" :http-request="planeUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 xls/xlsx/pdf/dwg格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
            <el-alert style="margin-bottom: 15px" type="error" v-if="errorBox" :closable="false">
              <template slot="title">
                <div class="iconSize">信息提示:</div>
                <div class="iconSize" v-for="(item,index) in errorList">({{index+1}}){{item}}</div>
              </template>
            </el-alert>
            <el-form-item label="三维图纸" prop="threeFiles" ref="threeElement">
              <el-upload class="avatar-uploader" action="#" drag ref="threeUpload" :auto-upload="true" :multiple="true"
                :file-list="threeFileList" :on-preview="handlePreview" :http-request="dimensionalUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">只能上传 三维图格式得文件</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitAttach('attachFormRef')" :loading="btnLoading" size="small" icon="el-icon-check">提 交
            </el-button>
            <el-button @click="attachBox = false" size="small" icon="el-icon-close">取 消</el-button>
          </span>
        </template>

      </el-dialog>
    </div>

    <div v-if="historyApprovalBox">
      <el-dialog title="历史审批记录" :visible.sync="historyApprovalBox" append-to-body width="80%" v-drag-dialog center
        :close-on-click-modal='false'>
        <avue-crud :data="historyData" :option="historyOption" v-model="historyForm" ref="historyTable"
          style="margin-top: -27px;">
        </avue-crud>
      </el-dialog>
    </div>

  </basic-container>
</template>

<script>
  import { historyFlowList, leaveDetail } from "@/api/work/process";
  import { getDrawingApprovalDetail } from "@/api/drawing/drawingapproval";
  import { completeTask } from "@/api/work/work";
  import { getPdfByUploadId, getThreeByUploadId, submitSignAttach, findDrawingListByUploadId, deleteDrawingAttach } from "@/api/drawing/drawingupload";
  import { updateDrawingStatus } from "@/api/drawing/drawingupload";
  import { handleDrawingAttachApproval, findHistoryApprovalList, handleDrawingAttachApprovalByBatch } from "@/api/drawing/drawingattachapproval";
  import { getToken } from '@/util/auth';

  export default {
    data() {
      // 上传附件验证
      let checkAttachFiles = (rule, value, callback) => {
        if (!this.$refs.fileUpload.uploadFiles.length) {
          callback(new Error('请选择要上传的文件'));
        } else {
          callback();
        }
      };
      
      return {
        btnLoading: false,
        resultForm: 1,
        resultDic: [{
          label: '同意',
          value: 0
        }, {
          label: '驳回',
          value: 1
        }],
        drawingData: [],
        drawingForm: {},
        drawingOption: {
          menu: false,
          tip: false,
          selection: true,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          saveBtn: false,
          updateBtn: false,
          cancelBtn: false,
          addBtn: false,
          delBtn: false,
          editBtn: false,
          page: false,
          align: 'center',
          menuAlign: 'center',
          index: true,
          indexLabel: '序号',
          height: 500,
          calcHeight: 500,
          column: [
            {
              label: "图纸名称",
              prop: "originalName",
              slot: true,
              width: 350
            },
            {
              label: "图纸类型",
              prop: "type",
              width: 220
            },
            {
              label: "审批结果",
              prop: "approvalResult",
              slot: true,
              width: 220
            },
            {
              label: "审批意见",
              prop: "approvalOpinion",
              slot: true
            }
          ]
        },
        selectionList: [],
        dimensionalUploadForm: new FormData(),
        uploadForm: new FormData(),
        dimensionalAttachBox: false,
        threeFileList: [],
        planeAttachBox: false,
        attachBox: false,
        attachForm: {
          attchFiles: '',
          threeFiles: '',
        },
        fileList: [],

        taskId: '',
        businessId: '',
        processInstanceId: '',
        taskDefinitionKey: '',
        src: '',
        flowList: [],
        form: {
          applicantName: '',
          comment: '',
          approvalOpinion: '',
          drawingNumber: '',
          drawingName: ''
        },
        approvalInfo: false,
        processInfo: false,
        processTrackInfo: false,
        planeDrawInfo: false,
        dimensionalDrawInfo: false,
        planeDrawingList: [],
        dimensionalDrawingList: [],
        planeAttach: {
          id: '',
          originalName: ''
        },
        dimensionalAttach: {
          id: '',
          originalName: ''
        },
        approvalButton: 'inline-block',
        uploadButton: 'none',
        eleList: [],

        historyForm: {},
        historyOption: {
          menu: false,
          tip: false,
          selection: false,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          saveBtn: false,
          updateBtn: false,
          cancelBtn: false,
          addBtn: false,
          delBtn: false,
          editBtn: false,
          page: false,
          align: 'center',
          menuAlign: 'center',
          index: false,
          indexLabel: '序号',
          height: 550,
          calcHeight: 'auto',
          column: [
            {
              label: "图纸名称",
              prop: "originalName",
              width: 300,
            },
            {
              label: "图纸类型",
              prop: "type",
              width: 200,
            },
            {
              label: "审批流程",
              prop: "taskDefinitionStr",
              width: 200
            },
            {
              label: "审批结果",
              prop: "approvalResultStr",
              width: 200,
            },
            {
              label: "审批意见",
              prop: "approvalOpinion",
            },
            {
              label: "审批时间",
              prop: "createTime",
              width: 200,
            }
          ]
        },
        historyData: [],
        historyApprovalBox: false,
        ruleForm: {
          attchFiles: [
            { validator: checkAttachFiles, required: true },
          ],
        },
        errorBox: false,
        errorList: [],
      }
      
    },
    created() {
      this.init();
    },
    beforeRouteUpdate(to, from, next) {
      // 在当前路由改变，但是该组件被复用时调用
      // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候
      // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用
      // 可以访问组件实例 `this`
      if (to.fullPath !== from.fullPath) {
        next();
        this.init();
      }
    },
    methods: {
      handleDrawingApproval(row) {
        let approvalResult = row.approvalResult;
        let approvalOpinion = row.approvalOpinion;
        if (approvalResult === undefined && approvalOpinion === undefined) {
          return;
        }
        if (approvalOpinion != null && approvalResult === undefined) {
          this.$message.warning("请输入图纸[ " + row.originalName + " ]审批结果!");
          //return;
        }
        if (approvalResult != null && approvalResult === '0' && (approvalOpinion === undefined || approvalOpinion === '')) {
          this.$message.warning("请输入图纸[ " + row.originalName + " ]审批意见!");
          //return;
        }
        let form = {};
        form.uploadId = this.$route.params.drawingUploadId;
        form.attachId = row.id;
        form.approvalResult = approvalResult;
        form.approvalOpinion = approvalOpinion;
        form.taskDefinitionKey = this.$route.params.taskDefinitionKey;
        handleDrawingAttachApproval(form).then();
      },
      handleApproval() {
        this.$confirm("确定将所有图纸进行审核?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      downloadList() {
        this.$confirm("确定下载已选择的图纸?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }).then(() => {
          let ids = [];
          if(this.selectionList.length!=0){
            this.selectionList.forEach(ele => {
              ids.push(ele.id);
            });
          } else{
            this.$message.error("请至少勾选一张图纸")
            return;
          }
          
          debugger 
          let drawingNumber = this.form.drawingNumber;
          location.href = `/api/blade-resource/attach/downloadInName?${this.website.tokenHeader}=${getToken()}&ids=` + ids.join(",") + `&patchName=${drawingNumber}`;
        });
      },
      downloadByBom() {
        this.$confirm("确定下载已归档图纸?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }).then(() => {
           
          let drawingNumber = this.form.drawingNumber;
          // location.href = `/api/blade-resource/attach/downloadByBom?${this.website.tokenHeader}=${getToken()}&drawNum=${drawingNumber}`;
          this.downloadAttach(`/api/blade-resource/attach/downloadByBom?drawNum=${drawingNumber}`)
        });
      },
      downloadAttach(url){
        this.axios
        .get(url, {
            headers: {
                'Content-Type': "application/x-download",
                token: sessionStorage.getItem('token') 
            },
            responseType: 'blob'
        })
        .then(res => {
          const responseType = res.data.type;
          
          if (responseType.includes('application/x-download')) { // 响应类型为rar文件
            var filename = decodeURI(res.headers["content-disposition"].split("filename=")[1])
            let blob = new Blob([res.data], {
                type: 'application/x-rar-compressed'
              });
              if (window.navigator.msSaveOrOpenBlob) {
                  // 兼容IE10
                  window.navigator.msSaveBlob(blob);
              } else {
                  //  兼容chrome/firefox
                  let aTag = document.createElement('a');
                  aTag.download = filename;
                  aTag.href = window.URL.createObjectURL(blob);
                  aTag.click();
                  URL.revokeObjectURL(aTag.href);
              }
            return
          }
          if (responseType.includes('application/json')) { //响应类型为json
            var reader = new FileReader()
            reader.readAsArrayBuffer(res.data);
            reader.onload  = e => {
              var init = new Uint8Array(e.target.result);
              var result = JSON.parse(new TextDecoder('UTF-8').decode(init));
              this.$message.error(result.data)
            }
          }
        })
        .catch(function(message) {
          debugger
            //如果不能正常下载给出对应提示
            this.$warning.error(message)
        });
      },
      selectionChange(val) {
        this.selectionList = val;
      },
      // 提交附件信息
      submitAttach(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 测试环境中验证文件
            if (len <= 0) {
              this.$message.warning("请上传签名后的平面图纸!");
              return;
            }
            // 二维图纸
            let len = this.$refs['fileUpload'].$children[0].fileList.length;
            let fileList = this.$refs['fileUpload'].$children[0].fileList;
            // 三维图纸
            let threeLen = this.$refs['threeUpload'].$children[0].fileList.length;
            let threeFileList = this.$refs['threeUpload'].$children[0].fileList;
            this.taskDefinitionKey = this.$route.params.taskDefinitionKey;
            let originalFileLen = this.drawingData.length;
            if (this.taskDefinitionKey !== "applicantModify") {
              if (originalFileLen !== (len + threeLen)) {
                this.$message.error("原始图纸数量和签名后的图纸数量不匹配，请重新上传!")
                return;
              }
              for (let i = 0; i < this.drawingData.length; i++) {
                let originalName = this.drawingData[i].originalName;
                let originalDrawingNumber = originalName.substring(0, 13);
                let originalNameArr = originalName.split(".");
                let originalType = originalNameArr[originalNameArr.length - 1];
                let checkResult = false;

                for (let j = 0; j < fileList.length; j++) {
                  let targetName = fileList[j].name;
                  let targetDrawingNumber = targetName.substring(0, 13);
                  let targetNameArr = targetName.split(".");
                  let targetType = targetNameArr[targetNameArr.length - 1];
                  if (targetDrawingNumber === originalDrawingNumber && targetType === originalType) {
                    checkResult = true;
                    break;
                  }
                }
                if (!checkResult) {
                  for (let j = 0; j < threeFileList.length; j++) {
                    let targetName = threeFileList[j].name;
                    let targetDrawingNumber = targetName.substring(0, 13);
                    let targetNameArr = targetName.split(".");
                    let targetType = targetNameArr[targetNameArr.length - 1];
                    if (targetDrawingNumber === originalDrawingNumber && targetType === originalType) {
                      checkResult = true;
                      break;
                    }
                  }
                }
                if (!checkResult) {
                  this.$message.error("缺少" + originalName + "图纸，请重新上传!");
                  return;
                }
              }
            } else {
              let result = this.checkFile(fileList);
              if (result.length) {
                this.errorBox = true;
                this.errorList = result;
                return;
              }
            }

            // 重新封装二维图纸内容
            this.uploadForm.delete("planeFile");
            for (let k = 0; k < len; k++) {
              this.uploadForm.append("planeFile", this.$refs['fileUpload'].$children[0].fileList[k].raw);
            }

            // 重新封装三维图纸内容
            this.uploadForm.delete("dimensionalFile");
            for (let k = 0; k < threeLen; k++) {
              this.uploadForm.append("dimensionalFile", this.$refs['threeUpload'].$children[0].fileList[k].raw);
            }

            // 图纸上传id
            this.uploadForm.append("drawingUploadId", this.$route.params.drawingUploadId);
            // 附件id
            //this.uploadForm.append("attachId", this.planeAttach.id);
            this.uploadForm.append("taskDefinitionKey", this.$route.params.taskDefinitionKey);
            this.btnLoading = true;
            submitSignAttach(this.uploadForm).then((res) => {
              this.loading = true;
              if (res.data.data.error != null) {
                if (res.data.data.error.length) {
                  this.errorBox = true;
                  this.errorList = [];
                  for (let i = 0; i < res.data.data.error.length; i++) {
                    this.errorList.push(res.data.data.error[i]);
                  }
                  this.loading = false;
                }
              }
              if (res.data.data.right != null) {
                this.completeAgreeProcess();
                this.handleDrawingAttachApprovalByBatch(this.eleList);
                //this.$refs['fileUpload'].$children[0].fileList = [];
                this.uploadForm = new FormData();
                this.attachBox = false;
                this.btnLoading = false;
                this.onLoad(this.page);
                this.$message({type: "success",message: "上传成功!"});
              }
            })
          }
        });
      },
      completeAgreeProcess() {
        const flow = {
          taskId: this.taskId,
          processInstanceId: this.processInstanceId,
          taskDefinitionKey: this.taskDefinitionKey,
          comment: this.comment,
          flag: 'ok',
        };
        const drawingUpload = {
          flow: flow,
          id: this.$route.params.drawingUploadId
        }
      
        updateDrawingStatus(drawingUpload).then(res => {
          const data = res.data;
          if (data.success) {
            this.$message.success(data.msg);
            this.$router.$avueRouter.closeTag();
            this.$router.go(-1);
          } else {
            this.$message.error(data.msg || '提交失败');
          }
        });
      },
      // 二维图纸上传指定文件的url地址 pdf dwg xls xlsx
      planeUpload(file) {
        this.uploadForm.append("planeFile", file.file);
      },
      // 三维图纸上传
      dimensionalUpload(file) {
        this.uploadForm.append("dimensionalFile", file.file);
      },
      handleSuccess() {
        this.$refs.fileUpload.clearFiles();
      },
      checkFile(array) {
        let nameArray = new Array();
        for (let i = 0; i < array.length; i++) {
          let name = array[i].name.substring(0, 13);
          nameArray.push(name);
        }
        // 名称存在得个数
        let arr = this.checkNum(nameArray);
        // 返回值
        let returnValue = new Array();
        for (let j = 0; j < nameArray.length; j++) {
          if (arr[nameArray[j]] <= 1) {
            returnValue.push(nameArray[j] + "缺少其他附件资料");
          }
        }
        return returnValue;
      },
      // 数组中元素出现得个数
      checkNum(arr) {
        return arr.reduce(function (prev, next) {
          prev[next] = (prev[next] + 1) || 1;
          return prev;
        }, {});
      },
      uploadBefore() {
        this.fileList = [];
      },
      // 编辑状态提交成功
      editSuccess() {
        this.$refs.editFileUpload.clearFiles();
      },
      handlePreview(file) {
        let a = document.createElement('a');
        let event = new MouseEvent('click');
        a.download = file.name;
        a.href = file.url;
        a.dispatchEvent(event);
      },
      // 上传时变化
      uploadChange(file, fileList) {
        let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
        if (existFile) {
          fileList.pop();
          this.$message({
            type: "warning",
            message: file.name + "文件已存在!"
          });
        }
        this.fileList = fileList;
      },
      init() {
        this.taskId = this.$route.params.taskId;
        this.processInstanceId = this.$route.params.processInstanceId;
        this.businessId = this.$route.params.businessId;
        let drawingUploadId = this.$route.params.drawingUploadId;
        this.taskDefinitionKey = this.$route.params.taskDefinitionKey;
        // 设置同意按钮显示或隐藏
        if (this.taskDefinitionKey === "applicantModify") {
          this.approvalButton = 'none';
          this.uploadButton = 'inline-block';
        }

        this.src = `/api/blade-flow/process/diagram-view?processInstanceId=${this.$route.params.processInstanceId}`;
        historyFlowList(this.processInstanceId).then(res => {
          const data = res.data;
          if (data.success) {
            this.flowList = data.data;
          }
        })
        getDrawingApprovalDetail(this.businessId).then(res => {
          const data = res.data;
          if (data.success) {
            this.form = data.data;
          }
        })
        /* // 平面图纸页面展示数据
         this.getPdfByUploadId(drawingUploadId);
         // 三维图纸页面展示数据
         this.getThreeByUploadId(drawingUploadId);*/
        // 上传文件的所有图纸
        this.findDrawingListByUploadId(drawingUploadId);
      },
      findDrawingListByUploadId(drawingUploadId) {
        findDrawingListByUploadId(drawingUploadId, this.taskDefinitionKey).then(res => {
          this.drawingData = res.data.data;
          this.drawingData.forEach(ele => {
            this.$set(ele, 'approvalResult', ele.approvalResult);
          });
        })
      },
      // 平面图纸
      getPdfByUploadId(drawingUploadId) {
        getPdfByUploadId(drawingUploadId).then(res => {
          const data = res.data.data;
          this.planeDrawingList = data;
          this.drawingData = data;
        })
      },
      // 三维图纸
      getThreeByUploadId(drawingUploadId) {
        getThreeByUploadId(drawingUploadId).then(res => {
          const data = res.data.data;
          this.dimensionalDrawingList = data;
        })
      },
      //提交审核
      submitReview(){
        this.$confirm("确定提交审核意见?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=>{
            var flag = 0;
            var breakFlag = false;
            let result = true;
            for (let i = 0; i < this.drawingData.length; i++) {
              let approvalResult = parseInt(this.drawingData[i].approvalResult);
              let approvalOpinion = this.drawingData[i].approvalOpinion;
              if (approvalResult === -1) {
                this.$message.error("存在未审批的图纸禁止操作!");
                breakFlag = true;
                break;
              } else if (approvalResult === 0 & (approvalOpinion == "" || typeof(approvalOpinion) == "undefined")) {
                result = false;
                this.$message.warning("存在驳回但未填写审批意见的图纸!");
                breakFlag = true;
                break;
              } else if (approvalResult === 0) {
                flag += 1;
                result = false;
              }
            }
            if (breakFlag){
              return;
            }
            let dataList = new Array();
            this.drawingData.forEach(ele => {
              this.drawingApprovalByBatch(ele, dataList);
            });
            this.uploadForm = new FormData();
            this.fileList = [];
            debugger
            if(result & flag === 0){
              this.attachBox = true;
              return this.eleList = dataList;
            } else if( flag > 0 & !result ){
              handleDrawingAttachApprovalByBatch(dataList).then(() => {
              return deleteDrawingAttach(this.$route.params.drawingUploadId, this.taskDefinitionKey)}).then(() => {
              return this.completeDisagreeProcess();
              })
            }
          });
      },
      //重新上传
      reUpload(){
        this.uploadForm = new FormData();
        this.fileList = [];
        this.attachBox = true;
      },
      drawingApprovalByBatch(row, dataList) {
        let approvalRes = true;
        let approvalResult = row.approvalResult;
        let approvalOpinion = row.approvalOpinion;
        if (approvalResult === undefined && approvalOpinion === undefined) {
          return;
        }
        if (approvalResult === -1) {
          this.$message.warning("存在未审批的图纸!");
          throw new Error('存在未审批的图纸');
        }
        if (approvalResult === 0 && (approvalOpinion == "" || typeof(approvalOpinion) == "undefined")) {
          this.$message.warning("存在驳回但未填写审批意见的图纸!");
          throw new Error('存在驳回但未填写审批意见的图纸');
        }
        let element = {};
        element.uploadId = this.$route.params.drawingUploadId;
        element.attachId = row.id;
        element.approvalResult = approvalResult;
        element.approvalOpinion = approvalOpinion;
        element.taskDefinitionKey = this.$route.params.taskDefinitionKey;
        return dataList.push(element);
      },
      handleHistoryApproval() {
        this.historyApprovalBox = true;
        let drawingUploadId = this.$route.params.drawingUploadId;
        findHistoryApprovalList(drawingUploadId, this.taskDefinitionKey).then(res => {
          let result = res.data.data;
          for (let i = 0; i < result.length; i++) {
            if (result[i].approvalResult === 0) {
              result[i].approvalResultStr = "驳回";
            } else if (result[i].approvalResult === 1) {
              result[i].approvalResultStr = "同意";
            }
            if (result[i].taskDefinitionKey === 'structureApproval') {
              result[i].taskDefinitionStr = "结构审批";
            } else if (result[i].taskDefinitionKey === 'processApproval') {
              result[i].taskDefinitionStr = "加工工艺审批";
            } else if (result[i].taskDefinitionKey === 'normalizing') {
              result[i].taskDefinitionStr = "标准化";
            }
          }
          this.historyData = result;
        })
      },
      completeDisagreeProcess() {
        const params = {
          taskId: this.taskId,
          processInstanceId: this.processInstanceId,
          taskDefinitionKey: this.taskDefinitionKey,
          //comment: this.form.approvalOpinion,
        };
        completeTask(params).then(res => {
          const data = res.data;
          if (data.success) {
            this.$message.success(data.msg);
            // $routers路由导航对象，利用他提转到不同的页面
            // $route是路由对象获取当前路由中的name\path\query\params
            this.$router.$avueRouter.closeTag();
            // this.$router.push({path: `/work/start`});
            this.$router.go(-1);
          } else {
            this.$message.error(data.msg || '提交失败');
          }
        })
      },
      handleCancel() {
        this.$router.$avueRouter.closeTag();
        // this.$router.push({path: `/work/start`});
        this.$router.go(-1);
      },
      approvalClick() {
        this.approvalInfo = !this.approvalInfo;
      },
      processClick() {
        this.processInfo = !this.processInfo;
      },
      processTrackClick() {
        this.processTrackInfo = !this.processTrackInfo;
      },
      planeDrawClick() {
        this.planeDrawInfo = !this.planeDrawInfo;
      },
      dimensionalDrawClick() {
        this.dimensionalDrawInfo = !this.dimensionalDrawInfo;
      },
    }
  }
</script>

<style>
  /*.approval_info .el-card__body{
    display: none;
  }*/
  .approval {
    display: none;
  }

  .process {
    display: none;
  }

  .processTrack {
    display: none;
  }

  .planeDraw {
    display: none;
  }

  .dimensionalDraw {
    display: none;
  }

  .avue-crud__menu {
    min-height: 0px;
  }

  .agree_active {
    display: none;
  }

  .upload_active {
    display: none;
  }
</style>